#!/usr/bin/env ruby
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.
# frozen_string_literal: true

require 'fileutils'
require 'optparse'
require 'json'
require 'securerandom'

require_relative 'lib/common'
require_relative 'lib/jwt'
require_relative '../lib/mq_client'
require_relative '../container/defconfig'

opt = {
  'compute': false,
  'is_remote' => false
}

options = OptionParser.new do |opts|
  opts.banner = 'Usage: multi-qemu -n -c -q -l -i -h'

  opts.separator ''
  opts.on('-n HOSTNAME_PREFIX', '--name HOSTNAME_PREFIX', 'format: $tbox_group.$HOSTNAME') do |name|
    opt['hostname_prefix'] = name
  end

  opts.on('-c count', '--count count', 'how many VM do you need') do |num|
    opt['nr_vm'] = num
  end

  opts.on('-q queues', '--queues queues', 'separated by ","') do |queues|
    opt['queues'] = queues
  end

  opts.on('-l log_dir', '--log_dir log_dir', 'directory for save qemu log') do |dir|
    opt['log_dir'] = dir
  end

  opts.on('-p', '--compute', 'set use compute max dc numbers by cpu and will ignore -c number') do
    opt['compute'] = true
  end

  opts.on('-r', '--remote', 'if testbox is a remote one') do
    opt['is_remote'] = true
  end

  opts.on_tail('-h', '--help', 'show this message') do
    puts opts
    exit
  end
end

if ARGV.size.zero?
  puts options
  exit 1
end

options.parse!(ARGV)

# Run multiple QEMU in parallel
PWD      = Dir.pwd
HOSTNAME = opt['hostname_prefix'] || "vm-2p8g.#{ENV['HOSTNAME']}"
QUEUES   = opt['queues'] || "#{ENV['HOSTNAME']}.#{RUBY_PLATFORM.split('-')[0]}"
LOG_DIR  = opt['log_dir'] || '/srv/cci/serial/logs'
COMPUTE_FLAG = opt['compute']
IS_REMOTE = opt['is_remote']

UUID = SecureRandom.uuid
SUITE_FILE = "/tmp/#{ENV['HOSTNAME']}/suite"
SAFE_STOP_FILE = "/tmp/#{ENV['HOSTNAME']}/safe-stop"
RESTART_FILE = "/tmp/#{ENV['HOSTNAME']}/restart/#{UUID}"
RESTART_LOCK_FILE = "/tmp/#{ENV['HOSTNAME']}/restart/lock"

names = Set.new %w[
  SCHED_HOST
  SCHED_PORT
  MQ_HOST
  MQ_PORT
]
defaults = relevant_defaults(names)

SCHED_HOST = ENV['LKP_SERVER'] || '172.17.0.1'
SCHED_PORT = ENV['LKP_CGI_PORT'] || '3000'
MQ_HOST = ENV['MQ_HOST'] || ENV['LKP_SERVER'] || '172.17.0.1'
MQ_PORT = ENV['MQ_PORT'] || 5672

if COMPUTE_FLAG
  puts 'auto compute max vm numbers'
  # base on vm-2p4g
  NR_VM = compute_max_vm
else
  NR_VM = opt['nr_vm'] || 1
end

def loop_main
  pwd_hostname = File.join(PWD, HOSTNAME)
  # pwd_hostname = File.join(PWD, "vm-2p8g-1")
  FileUtils.mkdir_p(pwd_hostname) unless File.exist?(pwd_hostname)

  system(
    { 'hostname' => HOSTNAME,
      'queues' => "#{QUEUES}",
      'max_vm' => NR_VM.to_s,
      'log_dir' => LOG_DIR,
      'UUID' => UUID,
      'is_remote' => IS_REMOTE.to_s,
      'WORKSPACE' => pwd_hostname,
    },
      #'vm_p' => VM_P.to_s,
      #'vm_m' => VM_M.to_s
    ENV['CCI_SRC'] + '/providers/qemu.rb'
  )
end

def multiqemu
  unless IS_REMOTE
    reboot_thr = Thread.new do
      loop_reboot_testbox(HOSTNAME, 'vm', MQ_HOST, MQ_PORT)
    end
  end

  threads = {}
  loop_main

  manage_thr = Thread.new do
    manage_multi_qemu_docker(threads.merge({ 'manage' => manage_thr }), MQ_HOST, MQ_PORT)
  end

  manage_thr.exit
  reboot_thr.exit
  puts 'all threads exit'

  safe_stop
  puts "#{UUID} exit"
end

if $PROGRAM_NAME == __FILE__
  save_running_suite
  init_specmeminfo(NR_VM, 'vm')
  multiqemu
end
